package com.gxa.ehome.controller;


import com.gxa.ehome.busiCodeEnum.ErrorCode;
import com.gxa.ehome.exception.BusinessException;
import com.gxa.ehome.util.MapUtil;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@ControllerAdvice
@ResponseBody
public class ExceptionController {
    //@ExceptionHandler(Throwable.class)  所有可抛出异常都会被该方法拦截
    //@ExceptionHandler(value=Throwable.class)
    @ExceptionHandler(value={Throwable.class})
    public Map<String,Object> exceptionHandle(Throwable throwable){
        //业务类型异常:给前端code./desc,给用户看
        //系统异常:500的状态告诉前端开发人员,给用户提示:系统发生未知问题,请稍后再试
        //再把系统完整的信息记录到日志
        MapUtil mapUtil = new MapUtil();

        if(throwable instanceof BusinessException){
            //给前端看
            ErrorCode errorCode = ((BusinessException) throwable).getErrorCode();
            mapUtil.setCode(errorCode.getCode());
            mapUtil.setMsg(errorCode.getDesc());
           // System.out.println("BusinessException异常");
        }else {
            //给前端看
            mapUtil.setCode("500");
            mapUtil.setMsg("系统发生未知异常");
           // System.out.println("Exception异常");
            //操作日志,将异常信息记录到日志文件:

            ((Exception)throwable).getMessage();
            ((Exception)throwable).toString();
            StackTraceElement[] stackTrace = throwable.getStackTrace();
            //在执行遍历操作,将每一个栈中的执行过程输出到日志
            for (StackTraceElement stackTraceElement : stackTrace) {


            }

        }

        return mapUtil.getValues();

    }
}
